<template>
  <div class="app-container" id="container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="70px"
             class="top-input">
      <el-form-item prop="cityCode" label="城市">
        <el-select v-model="queryParams.cityCode" placeholder="请选择城市" @change="getDistrict">
          <el-option
            v-for="dict in cityOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="行政区" prop="adcode">
        <el-select v-model="queryParams.adcode" placeholder="请选择行政区">
          <el-option
            v-for="district in districtOptions"
            :key="district.adcode"
            :label="district.name"
            :value="district.adcode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="乡镇属性" prop="districtPop">
        <el-select v-model="queryParams.districtPop" placeholder="请选择行政区">
          <el-option
            v-for="district in userPopOptions"
            :key="district.dictValue"
            :label="district.dictLabel"
            :value="parseInt(district.dictValue)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8 top-btn">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleOpenAdd"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <div id="district">
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="城市" prop="cityCode">
            <el-select v-model="form.cityCode" placeholder="请选择城市" @change="getDistrict">
              <el-option
                v-for="dict in cityOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区县" prop="adcode">
            <el-select v-model="form.adcode" placeholder="请选择区域">
              <el-option
                v-for="district in districtOptions"
                :key="district.adcode"
                :label="district.name"
                :value="district.adcode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleAddDistrict">确定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<style>
html, body, #container {
  width: 100%;
  margin: 0;
}

.top-btn {
  position: fixed;
  margin-bottom: 7px;
  z-index: 999;
  top: 150px;

}

.top-input {
  position: fixed;
  margin-bottom: 7px;
  z-index: 999;
}
</style>
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import $ from 'jquery';
import {saveDistricts, listDistrict, getDistrictByCity, delDistrict, resetDistrict} from "@/api/integration/district";

var map;
var mouseTool;
var districtSearch;
var contextMenu;
var rightClickPolygon;
var infoWindow;
export default {
  name: "District",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      districtList: [],
      userPopOptions: [],
      cityOptions: [],
      districtOptions: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {},
      // 围栏表单参数
      form: {},
      // 表单校验
      rules: {
        cityCode: [
          {required: true, message: "请选择城市", trigger: "blur"}
        ],
        adcode: [
          {required: true, message: "请选择区县", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.init();
    this.getDicts("city").then(response => {
      this.cityOptions = response.data;
    });
    this.getDicts("district_type").then(response =>{
      this.userPopOptions = response.data;
    })
  },
  methods: {
    init() {
      AMapLoader.load({
        "key": "3fa060bd1711d61ee47bb8983d7b1101",              // 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        "plugins": ['AMap.Scale', 'AMap.ToolBar', 'AMap.MouseTool', "AMap.DistrictSearch","AMap.GeometryUtil","AMap.PlaceSearch", "AMap.AutoComplete"],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        map = new AMap.Map('container', {
          resizeEnable: true,
          /*center: [116.471354, 39.994257],*/
          zoom: 8,
          showIndoorMap: false
        });
        infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
        map.addControl(new AMap.Scale())
        map.addControl(new AMap.ToolBar())
        mouseTool = new AMap.MouseTool(map);
        contextMenu = new AMap.ContextMenu();
        contextMenu.addItem("重置", this.handleReset, 0);
        // contextMenu.addItem("删除", this.handleDelete, 1);
        this.getList();
        var opts = {
          subdistrict: 0,   //获取边界不需要返回下级行政区
          showbiz: false,
          extensions: 'all',  //返回行政区边界坐标组等具体信息
          level: 'district'  //查询行政级别为 市
        };
        districtSearch = new AMap.DistrictSearch(opts);
        $("#container").css("height", (document.body.offsetHeight) - 85 + "px")
      }).catch(e => {
        console.log(e);
      })
    },
    initPolygon(district) {
      var str = district.ydistrictPoints.split(";");
      var path = [];
      for (var i = 0; i < str.length; i++) {
        var point = str[i].split(",");
        var zb = new AMap.LngLat(point[0], point[1])
        path.push(zb);
      }
      var polygon = new AMap.Polygon({
        path: path,
        fillColor: district.districtColor,
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: '#2b8cbe',
        strokeWeight: 1,
        strokeStyle: 'dashed',
        strokeDasharray: [5, 5],
        extData: {
          district: district
        }

      });
      polygon.content = '区县名称：'+district.districtName;
      map.add(polygon);
      polygon.on('click', this.polygonClick);
      polygon.on('rightclick', function (e) {
        rightClickPolygon = e.target;
        contextMenu.open(map, e.lnglat);
      });
    },
    polygonClick(e) {
      infoWindow.setContent(e.target.content);
      infoWindow.open(map, e.lnglat);
      contextMenu.close();
    },
    getList() {
      this.queryParams.districtLevel = 2;
      listDistrict(this.queryParams).then(response => {
        this.districtList = response.data;
        map.setCity(this.queryParams.cityCode);
        for (var i = 0; i < this.districtList.length; i++) {
          var table = this.districtList[i];
          this.initPolygon(table);
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      contextMenu.close();
      map.clearMap();
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleOpenAdd() {
      this.reset();
      this.open = true;
      this.title = "新增区域";
    },
    /** 添加区域按钮操作 */
    handleAddDistrict() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          var adcode = this.form.adcode;
          var adcodeName = "";
          var city = "";
          var cityCode = this.form.cityCode;
          var color = this.randomHexColor();
          this.districtOptions.forEach(item => {
            if (this.form.adcode == item.adcode) {
              adcodeName = item.name;
            }
          })
          this.cityOptions.forEach(item => {
            if (this.form.cityCode == item.dictValue) {
              city = item.dictLabel;
            }
          })
          //查询区域边界
          districtSearch.search(this.form.adcode, function (status, result) {
            var bounds = result.districtList[0].boundaries;
            if (bounds) {
              var districts = [];
              //将坐标数据保存到数据库
              for (var i = 0, l = bounds.length; i < l; i++) {
                //组装数据
                var path = bounds[i];
                var fenceDistrict = {};
                fenceDistrict.cityCode = cityCode;
                fenceDistrict.city = city;
                fenceDistrict.adcode = adcode;
                fenceDistrict.adcodeName = adcodeName;
                fenceDistrict.districtColor = color;
                var points = "";
                for(var j=0;j<path.length;j++){
                  if (j < path.length - 1) {
                    points = points+path[j].getLng()+","+path[j].getLat()+";"
                  } else {
                    points = points+path[j].getLng()+","+path[j].getLat();
                  }
                }
                fenceDistrict.ydistrictPoints = points;
                fenceDistrict.districtPoints = points;
                fenceDistrict.districtLevel = 2;
                districts.push(fenceDistrict);
              }
              saveDistricts(districts).then(response => {

              });
            }
          });
          this.handleQuery();
          this.msgSuccess("保存成功");
          this.open = false;
        }
      });
    },
    /** 重置围栏操作 */
    handleReset() {
      contextMenu.close();
      var district = rightClickPolygon.getExtData().district;
      this.$confirm('是否重置名称为' + district.districtName + '的数据项?该操作将会重置子区域', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return resetDistrict(district)
      }).then(() => {
        this.handleQuery();
        this.msgSuccess("重置成功");
      })
    },
    randomHexColor() { //随机生成十六进制颜色
      return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).substr(-6);
    },
    /** 删除按钮操作 */
    handleDelete() {
      contextMenu.close();
      var district = rightClickPolygon.getExtData().district;
      this.$confirm('是否确认删除名称为' + district.districtName + '的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delDistrict(district);
      }).then(() => {
        this.handleQuery();
        this.msgSuccess("删除成功");
      })
    },
    getDistrict(value) {
      var data = {};
      data.cityCode = value;
      this.cityOptions.forEach(item => {
        if (value == item.dictValue) {
          data.city = item.dictLabel;
          this.form.city = item.dictLabel;
          this.form.cityCode = item.dictValue;
        }
      })
      getDistrictByCity(data).then(response => {
        this.districtOptions = response.data;
      })
    },
  }
};
</script>
